package cwiczenia;

import javax.servlet.*;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginFilter implements Filter {


    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
                PrintWriter pw = response.getWriter();
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        HttpSession session = httpRequest.getSession();

        if (session.getAttribute("login") == null) {
            if (request.getParameter("user") == null || request.getParameter("pass") == null)
                pw.print("<html><body><h1>Niezalogowany</h1>" +
                        "<form method=\"POST\"" + " action=\"" + httpRequest.getServletPath() + "\">" +
                        "user: <input type=\"text\" size=\"20\" name=\"user\"><br/>" +
                        "pass: <input type=\"password\" size=\"20\" name=\"pass\"><br/>" +
                        "<input type=\"submit\" name=\"submit\" Value=\"Submit\">" +
                        "</form>" +
                        "</body></html>");
            else {
                if (userOK(request.getParameter("user"), request.getParameter("pass"))) {
                    session.setAttribute("login", request.getParameter("user"));
                    filterChain.doFilter(request, response);            
                } else {
                    pw.print("Hehe... ]:->");
                }
            }

        } else {
            filterChain.doFilter(request, response);
        }

        pw.close();
    }

    private boolean userOK(String parameter, String parameter1) {
        return parameter.equals(parameter1);
    }

    public void destroy() {
    }
}
